package com.zengzhi.mydesignmode.observermode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiejiawei
 * @Date 2021-08-16
 * @Time 21:40
 */
public class WeatherData implements Subject {

    /**
     * 用一个集合才存储所有的观察者
     */
    private List observers;

    /**
     * 温度
     */
    private float temperature;

    /**
     * 湿度
     */
    private float humidity;

    /**
     * 压力
     */
    private float pressure;

    public WeatherData(){
        observers = new ArrayList();
    }
    /**
     * 注册观察者
     *
     * @param observer
     */
    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    /**
     * 移除观察者
     *
     * @param observer
     */
    @Override
    public void removeObserver(Observer observer) {
        int index = observers.indexOf(observer);
        if (index >= 0) {
            observers.remove(index);
        }

    }

    /**
     * 通知观察者
     */
    @Override
    public void notifyObserver() {
        for (int i = 0; i < observers.size(); i++) {
            Observer o = (Observer) observers.get(i);
            o.update(temperature, humidity, pressure);
        }
    }

    /**
     * 当数据更新时，执行通知所有观察者
     */
    public void measurementsChanged(){
        notifyObserver();
    }

    public void setMeasurements(float temperature, float humidity, float pressure){
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}
